//
//  QQManager.m
//  SNS
//
//  Created by  on 11-11-10.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "QQManager.h"
#import "NSURL+QAdditions.h"
#import "QWeiboSyncApi.h"
#import "AppDelegate.h"
#import "QVerifyWebViewController.h"
#import "QWeiboAsyncApi.h"
#import "QWeiboRequest.h"
#import "QOauthKey.h"
#import "TKAlertCenter.h"
#import "Reachability.h"

@implementation QQManager

static QQManager* qqManagerSingleton = nil;

@synthesize tokenKey;
@synthesize tokenSecret;
@synthesize connection;
@synthesize responseData;
@synthesize delegate;
@synthesize finishCallback;
@synthesize failCallback;

#pragma mark - private methods

- (void)loadDefaultKey {	
	self.tokenKey = [[NSUserDefaults standardUserDefaults] valueForKey:AppTokenKey];
	self.tokenSecret = [[NSUserDefaults standardUserDefaults] valueForKey:AppTokenSecret];
}


#pragma mark - public methods

+ (QQManager *) sharedManager {
    if (!qqManagerSingleton) {
        qqManagerSingleton = [[QQManager alloc] init];
    }
    return qqManagerSingleton;
}

- (id) init {
    self = [super init];
    if (self) {
        [self loadDefaultKey];
    }
    return self;
}

- (void)dealloc {
	[tokenKey release];
	[tokenSecret release];
    [connection release];
    [responseData release];
	
    [super dealloc];
}

- (BOOL) isUserLoggedin {
    if (self.tokenKey && self.tokenSecret) {
        return YES;
    }
    else {
        return NO;
    }
}


- (void) login {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    if (![self isUserLoggedin]) {
        
        QVerifyWebViewController *verifyController = 
        [[QVerifyWebViewController alloc] init];
        UINavigationController *navigationController = [[[UINavigationController alloc]
                                                         initWithRootViewController:verifyController] autorelease];
        navigationController.navigationBar.barStyle = UIBarStyleBlack;
        
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appDelegate.window.rootViewController presentModalViewController:navigationController 
                                                                 animated:YES];
        [verifyController release];
    }
}

- (void) logout {
    self.tokenKey = nil;
    self.tokenSecret = nil;
    [self saveDefaultKey];
    
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"退出成功！"
                                                  image:[UIImage imageNamed:@"tengxunIcon.png"]];
}

- (void) updateStatus: (NSString *)newStatus 
             delegate:(id)aDelegate 
       finishCallback:(SEL)aFinishCallback 
         failCallback:(SEL)aFailCallback {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    self.delegate = aDelegate;
    self.finishCallback = aFinishCallback;
    self.failCallback = aFailCallback;
    
    QWeiboAsyncApi *api = [[[QWeiboAsyncApi alloc] init] autorelease];
    
	self.connection	= [api publishMsgWithConsumerKey:AppKey 
									  consumerSecret:AppSecret 
									  accessTokenKey:self.tokenKey 
								   accessTokenSecret:self.tokenSecret 
											 content:newStatus 
										   imageFile:nil
										  resultType:RESULTTYPE_JSON 
											delegate:self];
}

- (void) sendImage:(UIImage *)image 
           withMsg:(NSString *)msg 
          delegate:(id)aDelegate 
    finishCallback:(SEL)aFinishCallback 
      failCallback:(SEL)aFailCallback {
    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"没有网络！"];
        return;
    }
    
    self.delegate = aDelegate;
    self.finishCallback = aFinishCallback;
    self.failCallback = aFailCallback;
    
    QWeiboAsyncApi *api = [[[QWeiboAsyncApi alloc] init] autorelease];
	
    NSString *imageFilePath = [NSTemporaryDirectory() stringByAppendingFormat:@"temp.png"];
    [UIImagePNGRepresentation(image) writeToFile:imageFilePath atomically:YES];
    
	self.connection	= [api publishMsgWithConsumerKey:AppKey 
									  consumerSecret:AppSecret 
									  accessTokenKey:self.tokenKey 
								   accessTokenSecret:self.tokenSecret 
											 content:msg 
										   imageFile:imageFilePath
										  resultType:RESULTTYPE_JSON 
											delegate:self];
}


- (void)parseTokenKeyWithResponse:(NSString *)aResponse {
	
	NSDictionary *params = [NSURL parseURLQueryString:aResponse];
	self.tokenKey = [params objectForKey:@"oauth_token"];
	self.tokenSecret = [params objectForKey:@"oauth_token_secret"];
	
}

- (void)saveDefaultKey {
	
	[[NSUserDefaults standardUserDefaults] setValue:self.tokenKey forKey:AppTokenKey];
	[[NSUserDefaults standardUserDefaults] setValue:self.tokenSecret forKey:AppTokenSecret];
	[[NSUserDefaults standardUserDefaults] synchronize];
}

//- (void)getVideoData:(NSString *)videoURL 
//        withDelegate:(id)aDelegate 
//      finishCallback:(SEL)aFinishCallback 
//        failCallback:(SEL)aFailCallback {
//    
//    self.delegate = aDelegate;
//    self.finishCallback = aFinishCallback;
//    self.failCallback = aFailCallback;
//    
//    QWeiboRequest *request = [[[QWeiboRequest alloc] init] autorelease];
//    
//    QOauthKey *oauthKey = [[QOauthKey alloc] init];
//	oauthKey.consumerKey = AppKey;
//	oauthKey.consumerSecret = AppSecret;
//	oauthKey.tokenKey = self.tokenKey;
//	oauthKey.tokenSecret= self.tokenSecret;
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:@"json" forKey:@"format"];
//    [params setObject:videoURL forKey:@"url"];
//    
//    self.connection = [request asyncRequestWithUrl:@"http://open.t.qq.com/api/t/getvideoinfo"
//                                        httpMethod:@"POST"
//                                          oauthKey:oauthKey
//                                        parameters:params
//                                             files:nil
//                                          delegate:self];
//}
//
//- (NSString *)getVideoData:(NSString *)videoURL {
//    QWeiboRequest *request = [[[QWeiboRequest alloc] init] autorelease];
//    
//    QOauthKey *oauthKey = [[QOauthKey alloc] init];
//	oauthKey.consumerKey = AppKey;
//	oauthKey.consumerSecret = AppSecret;
//	oauthKey.tokenKey = self.tokenKey;
//	oauthKey.tokenSecret= self.tokenSecret;
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    [params setObject:@"json" forKey:@"format"];
//    [params setObject:videoURL forKey:@"url"];
//    
//    return [request syncRequestWithUrl:@"http://open.t.qq.com/api/t/getvideoinfo"
//                            httpMethod:@"POST"
//                              oauthKey:oauthKey
//                            parameters:params
//                                 files:nil];
//}

#pragma mark - Request Callback

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	self.responseData = [NSMutableData data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
	NSString *response = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
//	NSLog(@"success %@", response);
	self.connection = nil;
    
    if (self.delegate && [self.delegate respondsToSelector:self.finishCallback]) {
        [self.delegate performSelector:self.finishCallback withObject:response];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	NSString *errorInfo = [NSString stringWithFormat:@"connection error:%@", error];
//	NSLog(@"fail %@", errorInfo);
	self.connection = nil;
    
    if (self.delegate && [self.delegate respondsToSelector:self.failCallback]) {
        [self.delegate performSelector:self.failCallback withObject:errorInfo];
    }
}


@end
